package com.example.demo.grpc.utils;

import com.example.demo.HeaderReq;
import com.example.demo.HeaderRes;
import com.example.demo.Request;
import com.example.demo.Response;
import com.google.protobuf.Any;
import com.google.protobuf.Message;

import java.util.Objects;
import java.util.UUID;

/**
 * 消息构建器
 * @author ls
 */
public class MsgBuilder {

    /**
     * 构建请求报文
     * @param data  业务报文
     * @param userId 用户id
     * @return 请求
     */
    public static Request buildReq(Message  data, String userId) {
        return Request.newBuilder()
                .setHead(buildHeaderReq(userId))
                .setBody(Any.pack(data))
                .build();
    }

    public static Request buildReq(Message data) {
        return buildReq(data, null);
    }

    /**
     * 构建成功响应
     * @param data 业务报文
     * @param code 状态码
     * @param msg  状态描述
     * @return 响应
     */
    public static Response buildRes(Message data, String code, String msg) {
        Response.Builder builder = Response.newBuilder()
                .setHead(buildHeaderRes(code, msg));
        if (!Objects.isNull(data)) {
            builder.setBody(Any.pack(data));
        }
        return builder.build();
    }

    public static Response success(Message message) {
        return buildRes(message, "200", "success");
    }

    public static Response fail(String code, String msg) {
        return buildRes(null, code, msg);
    }

    public static Response fail(String msg) {
        return buildRes(null, "500", msg);
    }


    /**
     * 构建响应头
     * @param code 状态码
     * @param msg  状态描述
     * @return 响应头
     */
    private static HeaderRes.Builder buildHeaderRes(String code,  String msg) {
        HeaderRes.Builder builder = HeaderRes.newBuilder().setCode(code);
        if (!Objects.isNull(msg)) {
            builder.setMsg(msg);
        }
        return builder;
    }

    /**
     * 构建请求头
     * @param traceId
     * @return 请求头
     */
    private static HeaderReq.Builder buildHeaderReq(String traceId) {
        HeaderReq.Builder builder = HeaderReq.newBuilder()
                .setTraceId(UUID.randomUUID().toString());
        if (!Objects.isNull(traceId)) {
            builder.setTraceId(traceId);
        }
        return builder;
    }
}
